//
//  RJCStationVC.m
//  AirQuality
//
//  Created by Po on 15/8/25.
//  Copyright (c) 2015年 Po. All rights reserved.
//

#import "RJCStationVC.h"
#import "RJCStationHelper.h"
#import "RJHomeTopSectionView.h"
#import "RJCityView.h"
#import "RJCStationLineView.h"

@interface RJCStationVC () <RJHomeTopSectionViewDelegate,RJCityViewDelegate, UIScrollViewDelegate>

@property (retain, nonatomic) RJCStationHelper * helper;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *scrollViewWidth;
@property (weak, nonatomic) IBOutlet UILabel *unitLable;

@property (retain, nonatomic) RJHomeTopSectionView * sectionView;
@property (retain, nonatomic) RJCityView * cityView;
@property (retain, nonatomic) UIView * touchView;

@property (retain, nonatomic) RJCStationLineView * lineView;

@property (retain, nonatomic) RJLoadView * myLoadView;
@property (retain, nonatomic) UILabel * updateLabel;
@property (assign, nonatomic) NSInteger loadCount;
@property (assign, nonatomic) BOOL isRunning;
@property (assign, nonatomic) BOOL willUpdate;
@property (assign, nonatomic) BOOL endDragging;
@end

@implementation RJCStationVC

- (void)viewDidLoad {
    [super viewDidLoad];
    _weatherDetailTextView.userInteractionEnabled = NO;
    _willUpdate = NO;
    _endDragging = NO;
    [self.navBar setReturnButtonHidden:NO];
    [self initInterface];
    [self reSetRadius];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    _isRunning = YES;
    [self doOneceNetRequest];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    _isRunning = NO;
}

- (void)updateViewConstraints
{
    [super updateViewConstraints];
    _scrollViewWidth.constant = ScreenWidth;
}

- (void)initInterface
{
//    self.unitLable.text = @"(co:mg/m³  其他:ug/m³)";
    [self.unitLable setAttributedText:[self getUmstr:@"(CO:mg/m³   其他:µg/m³)"]];
    [_scrollView setDelegate:self];
    [_scrollView addSubview:[self getUpdateLabel]];
    [_lineContentView addSubview:[self getSectionView]];
    dispatch_async(dispatch_get_main_queue(), ^{
        [_dateLabel setText:[RJTools getTimeWithFormat:@"hh:mm EEEE" time:[NSDate date]]];
    });
    
}

- (void)reSetRadius
{
    CGFloat radius = (ScreenWidth - 90) / 12;
    [_pm25TittleLabel.layer setCornerRadius:radius];
    [_pm10TittleLabel.layer setCornerRadius:radius];
    [_o3TittleLabel.layer setCornerRadius:radius];
    [_so2TittleLabel.layer setCornerRadius:radius];
    [_no2TittleLabel.layer setCornerRadius:radius];
    [_coTittleLabel.layer setCornerRadius:radius];
}
#pragma mark - function
- (void)doOneceNetRequest
{
    _loadCount = 2;
//    [self.view addSubview:[self getLoadView]];
    [MBProgressHUD showMessage:@"正在加载..."];
    if (_lineView) {
        [_lineView removeFromSuperview];
        _lineView = nil;
    }
    [_lineContentView addSubview:[self getLineBoxWithData:nil]];
    [_lineView setStatusString:@"正在获取数据，请稍等！"];
    
    __weak typeof(self) selfVC = self;
    [[self getModelHelper] doOneceNetRequestbasicBlock:^(BOOL result) {
        if (!_isRunning)
            return;
        
        if (result) {
            [selfVC setBasicData];
        }
        [self checkLoadViewRemove];
    } weatherBlock:^(BOOL result) {
        if (!_isRunning)
            return;
        if (result) {
            [selfVC setWeatherData];
        }
        [self checkLoadViewRemove];
    } lineBlock:^(BOOL result) {
        if (!_isRunning)
            return;
        if (result) {
            [selfVC resetLineViewWithKey:@"aqi"];
        } else {
            [_lineView setStatusString:@"获取数据失败"];
        }
    }];

}

- (void)checkLoadViewRemove
{
    _loadCount -- ;
    if (_loadCount <= 0) {
//        [_myLoadView removeSelf];
        [MBProgressHUD hideHUD];
    }
}

- (void)resetLineViewWithKey:(NSString *)key
{
    if (_lineView) {
        [_lineView removeFromSuperview];
        _lineView = nil;
    }
    @autoreleasepool {
        NSArray * times = _helper.model.lineData[@"times"];
        if (times.count == 0) {
            [_lineContentView addSubview:[self getLineBoxWithData:nil]];
            [_lineView setStatusString:@"获取数据失败"];
        } else {
            [_lineContentView addSubview:[self getLineBoxWithData:@{@"data":@[
                                                    @{key:_helper.model.cityData[key]},
                                                                            @{key:_helper.model.lineData[key]},
                                                                            @{key:[self getDeviationData:key]
                                                                                }],
                                                                            
                                                    @"times":times}]];
        }
    }
}

/**计算偏差折线数据*/
- (NSArray *)getDeviationData:(NSString *)key
{
    NSMutableArray * array = [NSMutableArray array];
    NSArray * lineData = _helper.model.lineData[key];
    NSArray * cityData = _helper.model.cityData[key];
    for (NSUInteger i = 0; i < lineData.count; i ++) {
        CGFloat lineNum = [(lineData[i] == nil ? @"0" : lineData[i]) floatValue];
        CGFloat cityNum = [(cityData[i] == nil ? @"0" : cityData[i]) floatValue];
        CGFloat deviationNum = (lineNum == 0 ? 0 :((cityNum - lineNum) / lineNum));
        [array addObject:GetStringWithFloat(deviationNum)];
    }
    return array;
}

- (void)hideCityView
{
    [_touchView removeFromSuperview];
    [_cityView setViewFrame:NO];
}

- (void)setBasicData{
    [self.view addSubview:[self getCityView]];
    NSArray * rankArray = @[@"优",@"良",@"轻度",@"中度",@"重度",@"严重"];
    RJCStationModel * model = _helper.model;
    [self.navBar.centerCityLabel setText:model.currentStationName];
     NSInteger index = [rankArray indexOfObject:model.aqiRankValue];
    [_visibilityLabel setText:model.visibilityValue];
    [_pressureLabel setText:model.pressureValue];
    [_windDirectionLabel setText:model.windDirectionValue];
    [_windSpeedLabel setText:model.windSpeedValue];
    [_humidnessLabel setText:model.humidnessValue];
    
    [_AQIRankLabel setText:model.aqiRankValue];
    if (index > 1) {
        NSString * aqiStr = [NSString stringWithFormat:@"%@%@",model.aqiRankValue,@"污染"];
        [_AQIRankLabel setText:aqiStr];
    }
    NSArray *colorArray = [RJTools getColorArrayWithAlpha:1];
    _AQIRankLabel.backgroundColor = colorArray[index];
    _AQIRankLabel.layer.cornerRadius = 5.0;
    _AQIRankLabel.layer.masksToBounds = YES;
    [_pm25Label setText:model.pm25Value];
    [_pm10Label setText:model.pm10Value];
    [_o3Label setText:model.o3Value];
    [_so2Label setText:model.so2Value];
    [_no2Label setText:model.no2Value];
    [_coLabel setText:model.coValue];
  
    [_pm25TittleLabel setBackgroundColor:[RJTools getNewColorWithAirNum:[model.pm25Value floatValue] type:@"PM2.5" alpha:1]];
    [_pm10TittleLabel setBackgroundColor:[RJTools getNewColorWithAirNum:[model.pm10Value floatValue] type:@"PM10" alpha:1]];
    [_o3TittleLabel setBackgroundColor:[RJTools getNewColorWithAirNum:[model.o3Value floatValue] type:@"O3" alpha:1]];
    [_so2TittleLabel setBackgroundColor:[RJTools getNewColorWithAirNum:[model.so2Value floatValue] type:@"SO2" alpha:1]];
    [_no2TittleLabel setBackgroundColor:[RJTools getNewColorWithAirNum:[model.no2Value floatValue] type:@"NO2" alpha:1]];
    [_coTittleLabel setBackgroundColor:[RJTools getNewColorWithAirNum:[model.coValue floatValue] type:@"CO" alpha:1]];
}

- (void)setWeatherData{
    [_weatherLabel setText:_helper.model.weatherValue];
    [_temperatureLabel setText:[NSString stringWithFormat:@"%@˚",_helper.model.temValue]];
}

#pragma mark - section delegate
- (BOOL)HomeTopSectionView:(RJHomeTopSectionView *)sectionView didSelectCount:(NSUInteger)count isLeft:(BOOL)isLeft
{
    if (_helper.model.lineData == nil) {
        return NO;
    }
    NSArray * keys = @[@"aqi",@"so2",@"no2",@"co",@"o3",@"pm10",@"pm2.5"];
    [self resetLineViewWithKey:keys[count]];
    return YES;
}

#pragma mark - RJOutCityViewDelegate
- (void)didSelectedRow:(NSUInteger)rowNumber data:(NSDictionary *)data
{
    NSDictionary * dic = _helper.model.stations[rowNumber];
    NSArray * detailArray = [dic allValues][0];
    NSString * cityName = detailArray[1];
    cityName = [cityName substringToIndex:cityName.length - 1];
    [_helper setStationData:[[dic allKeys] lastObject] stationName:detailArray[0] cityName:cityName];
    [self doOneceNetRequest];
}

- (void)didPressCityBar:(BOOL)isShow
{
    if (isShow) {
        [self.view insertSubview:[self getTouchView] belowSubview:_cityView];
    } else {
        [[self getTouchView] removeFromSuperview];
    }
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (_endDragging) {
        if (scrollView.contentOffset.y == 0) {
            _endDragging = NO;
            [_updateLabel setText:@"下拉刷新"];
        }
        return;
    }
    
    if (!_willUpdate && scrollView.contentOffset.y < -44) {
        _willUpdate = YES;
        [_updateLabel setText:@"松开即可刷新"];
    } else if (_willUpdate && scrollView.contentOffset.y > -44) {
        _willUpdate = NO;
        [_updateLabel setText:@"下拉刷新"];
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    _endDragging = YES;
    if (scrollView.contentOffset.y < -44) {
        [self doOneceNetRequest];
    }
}

#pragma mark - getter
- (RJCStationHelper *)getModelHelper
{
    if (!_helper) {
        _helper = [[RJCStationHelper alloc] init];
    }
    return _helper;
}

- (RJHomeTopSectionView *)getSectionView
{
    if (!_sectionView) {
        NSArray * typeArray = @[@"AQI",@"SO₂",@"NO₂",@"CO",@"O₃",@"PM₁₀",@"PM"];
        _sectionView = [[RJHomeTopSectionView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 40) titles:typeArray];
        [_sectionView setBackgroundColor:GetRGBColor(245, 245, 245, 1)];
        [_sectionView setDelegate:self];
    }
    return _sectionView;
}

- (RJCityView *)getCityView
{
    if (!_cityView) {
        _cityView = [[RJCityView alloc] initWithFrame:CGRectMake(ScreenWidth - 75, 11, 63, 30)];
        [_cityView setData:_helper.model.stations];
        [_cityView setDelegate:self];
    }
    return _cityView;
}

- (RJCStationLineView *)getLineBoxWithData:(NSDictionary *)data
{
    if (!_lineView) {
        _lineView = [[RJCStationLineView alloc] initWithFrame:CGRectMake(0, 70, ScreenWidth, 200) data:data];
    }
    return _lineView;
}

- (UIView *)getTouchView
{
    if (!_touchView) {
        
        _touchView = [[UIView alloc] initWithFrame:self.view.bounds];
        UITapGestureRecognizer * gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideCityView)];
        [_touchView addGestureRecognizer:gesture];
    }
    return _touchView;
}

- (RJLoadView *)getLoadView
{
    if (!_myLoadView) {
        _myLoadView = [[RJLoadView alloc] initWithFrame:CGRectMake(0, 50, ScreenWidth, ScreenHeight - 50)];
    }
    return _myLoadView;
}

- (UILabel *)getUpdateLabel
{
    if (!_updateLabel) {
        _updateLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, -44, ScreenWidth, 44)];
        [_updateLabel setTextAlignment:NSTextAlignmentCenter];
        [_updateLabel setFont:[UIFont boldSystemFontOfSize:30]];
        [_updateLabel setText:@"下拉刷新"];
    }
    return _updateLabel;
}

- (NSMutableAttributedString *)getUmstr:(NSString *)titleString
{
    NSUInteger length = titleString.length;
    NSUInteger index = [titleString rangeOfString:@"("].location;
    NSMutableAttributedString * attr = [[NSMutableAttributedString alloc] initWithString:titleString];
    [attr addAttribute:NSFontAttributeName
                 value:[UIFont systemFontOfSize:12.0]
                 range:NSMakeRange(index,length-index)];
    return attr;
}

@end
